<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>博客主页</title>
    <link rel="stylesheet" href="../css/homepage.css">
    <link rel="stylesheet" href="../css/navbar.css">

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        /* 发布文章按钮样式 */
        #publish-article-button {
            position: fixed;
            bottom: 30px;
            right: 30px;
            background-color: #28a745;
            color: white;
            border: none;
            border-radius: 50%;
            width: 60px;
            height: 60px;
            font-size: 30px;
            cursor: pointer;
            box-shadow: 0 4px 6px rgba(0,0,0,0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            z-index: 1000;
            transition: background-color 0.3s;
        }

        #publish-article-button:hover {
            background-color: #218838;
        }
    </style>
</head>
<body>
<!-- 头部区域 -->
<header>
    <div class="header-content">
        <div class="user-info">
            <span id="nickname">加载中...</span>
        </div>
        <div class="header-buttons">
            <a href="personal-center.html" id="personal-center" class="header-button">个人中心</a>
            <a href="my-blogs.html" id="my-blogs-button" class="header-button">我的博客</a>
            <a href="homepage.html" id="home-button" class="header-button">返回主页</a>
            <button id="logout-button" class="header-button">注销</button>
        </div>
    </div>
</header>

<!-- 博客列表区域 -->
<main>
    <div id="blog-list">
        <h2>博客列表</h2>
        <ul id="blogs">
            <!-- 博客列表项将在这里通过AJAX填充 -->
        </ul>

        <div id="pagination">
            <button id="prev-page">上一页</button>
            <span id="page-number">第1页</span>
            <button id="next-page">下一页</button>
        </div>
    </div>
</main>

<!-- 发布文章按钮 -->
<button id="publish-article-button" title="发布文章">+</button>

<script>
    document.addEventListener('DOMContentLoaded', function () {
       // const address = "http://127.0.0.1:9000";
        const address = "http://192.168.137.1";
        let currentPage = 1;  // 当前页
        const pageSize = 10;   // 每页显示的博客数

        // 从cookie读取用户信息
        const username = getCookie('username');
        const nickname = getCookie('nickname');

        function getCookie(name) {
            const value = document.cookie;
            const parts = value.split('; ').find(part => part.startsWith(name + '='));
            if (parts) return decodeURIComponent(parts.split('=')[1]);
            return null;
        }

        // 如果用户未登录，重定向到登录页面
        if (!username || !localStorage.getItem('token')) {
            window.location.href = address + '/blog_system/index.html';  // 替换为实际登录页面 URL
        }

        // 显示个人信息
        if (nickname) {
            document.getElementById('nickname').textContent = nickname;  // 显示昵称
        }

        // 获取博客列表
        async function fetchBlogList(pageIndex) {
            try {
                const response = await fetch(`${address}/api/blog_system/article/queryPage/${pageIndex}`, {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                const data = await response.json();


                if (data.success && data.data) {
                    const blogs = data.data.records || [];  // 获取博客数据
                    const total = data.data.total || 0;    // 如果后端没有 totalPages，使用 total
                    const totalPages = Math.ceil(total / pageSize); // 计算总页数

                    // 清空博客列表
                    const blogListContainer = document.getElementById('blogs');
                    blogListContainer.innerHTML = '';

                    // 填充博客列表
                    blogs.forEach(blog => {
                        // 映射状态码到文字
                        let statusText = '';
                        switch (blog.status) {
                            case 0:
                                statusText = '草稿';
                                break;
                            case 1:
                                statusText = '发布';
                                break;
                            case 2:
                                statusText = '待审核';
                                break;
                            default:
                                statusText = '未知状态';
                        }
                        const blogItem = `
                            <li>
                                <a href="blog-detail.html?id=${blog.id.toString()}" class="blog-title">${blog.title}</a>
                                <div class="excerpt">${blog.excerpt}</div>
                                <div class="blog-info">
<!--                                    <span>状态: ${statusText}</span>-->
                                    <span>浏览次数: ${blog.viewCount}</span>
                                    <span>点赞次数: ${blog.likeCount}</span>
                                    <span>发布时间: ${new Date(blog.createTime).toLocaleDateString()}</span>
                                </div>
                            </li>
                        `;
                        blogListContainer.innerHTML += blogItem;
                    });

                    updatePagination(pageIndex, totalPages);  // 更新分页
                } else {
                    alert('加载博客列表失败: ' + (data.message || '未知错误'));
                }
            } catch (error) {
                console.error('请求博客列表失败:', error);
                alert('加载博客列表失败，请检查网络连接。');
            }
        }

        // 更新分页
        function updatePagination(current, total) {
            currentPage = current;
            document.getElementById('page-number').textContent = `第${current}页`;

            document.getElementById('prev-page').disabled = current <= 1;
            document.getElementById('next-page').disabled = current >= total;
        }

        // 点击上一页
        document.getElementById('prev-page').addEventListener('click', function() {
            if (currentPage > 1) {
                fetchBlogList(currentPage - 1);
            }
        });

        // 点击下一页
        document.getElementById('next-page').addEventListener('click', function() {
            fetchBlogList(currentPage + 1);
        });

        // 获取个人信息
        async function fetchUserInfo() {
            try {
                const response = await fetch(`${address}/api/blog_system/user/get_user`, {
                    headers: {
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    }
                });
                const data = await response.json();
                if (data.success) {
                    const user = data.data;
                    // 将昵称和用户名显示在页面
                    document.getElementById('nickname').textContent = user.nickname || '无昵称';
                } else {
                    alert('获取个人信息失败: ' + data.message);
                }
            } catch (error) {
                console.error('请求个人信息失败:', error);
                alert('获取个人信息失败，请检查网络连接。');
            }
        }

        // 注销功能
        async function handleLogout() {
            if (!confirm('确定要注销吗？')) {
                return;
            }

            try {
                const response = await fetch(`${address}/api/blog_system/user/logout`, {
                    method: 'GET', // 根据后端定义选择 GET 或 POST
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${localStorage.getItem('token')}`
                    },
                });
                const data = await response.json();
                if (data.success) {
                    // 清除本地存储和Cookie
                    localStorage.removeItem('token');
                    document.cookie = 'username=; Max-Age=0; path=/';
                    document.cookie = 'token=; Max-Age=0; path=/';

                    // 重定向到登录页面
                    window.location.href = address + '/blog_system/index.html';  // 替换为实际登录页面 URL
                } else {
                    alert('注销失败: ' + (data.message || '未知错误'));
                }
            } catch (error) {
                console.error('注销请求失败:', error);
                alert('注销失败，请检查网络连接。');
            }
        }

        // 绑定注销按钮事件
        const logoutButton = document.getElementById('logout-button');
        if (logoutButton) {
            logoutButton.addEventListener('click', handleLogout);
        }

        // 绑定“返回主页”按钮事件
        const homeButton = document.getElementById('home-button');
        if (homeButton) {
            homeButton.addEventListener('click', function() {
                window.location.href = './homepage.html';
            });
        }

        // 绑定“发布文章”按钮事件
        const publishButton = document.getElementById('publish-article-button');
        if (publishButton) {
            publishButton.addEventListener('click', function() {
                window.location.href = 'publish-article.html';
            });
        }

        // 加载个人信息和博客列表
        fetchUserInfo();
        fetchBlogList(currentPage);
    });
</script>
</body>
</html>
